<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\checkBrandForm;
use App\Http\Controllers\Common\ajaxReturnJsonContent;
use Illuminate\Support\Facades\Storage;
use App\Http\Controllers\Common\updateFormUnique;
use DB;

class BrandController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $name = $request->input('name', '%');
        $likeWhere = '%'.$name.'%';
        //查询出顶级分类
        $res = DB::table('shop_brand')->select('id', 'name', 'brandpic', 'desbrand', 'createtime')
                                      ->where('name','like', $likeWhere)
                                      ->paginate(3);
        return view('admin.brand',['res' => $res, 'likeWhere' => $likeWhere]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(checkBrandForm $request)
    {

        //存储要上传的数据
        $input = [];

        //接收品牌名称
        $input['name'] = $request->input('name');
        //接收品牌描述
        $content = $request->input('content');
        if ($content != null) {
            $input['desbrand'] = $content;
        }

        //上传文件
        $file = $request->file('brandpic')->store("public/brandpic");

        //处理好图片路径
        $filepath = 'storage'.ltrim($file, 'public');

        $input['brandpic'] = $filepath;

        //向数据库添加数据
        $id = DB::table('shop_brand')->insertGetId($input);

        $arr = ajaxReturnJsonContent::returnVal($id, '添加成功', '添加失败');

        //判断，值为2时即为数据插入失败
        if ($arr['code'] == 2) {
            //数据插入失败，删除上传的文件
            unlink(asset($filepath));
        }

        //返回结果给视图
        return redirect('admin/Brand')->with($arr);

    }

    /**
     * 用来判断品牌名是否存在
     *
     * @param  string  传过来的品牌名称
     * @return \Illuminate\Http\Response
     */
    public function show($BrandName)
    {
        $data = DB::table('shop_brand')->select('id')
                               ->where('name', $BrandName)
                               ->first();
        $arr = ajaxReturnJsonContent::returnVal($data, '品牌已存在', '可以使用');
        return json_encode($arr);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $arr = $request->all();
        $res = [];
        //判断是否有新的品牌名传过来
        if ($arr['updatename']) {
            if ($arr['updatename'] != $arr['oldName']) {
                $bool = updateFormUnique::dataUnique($arr['updatename']);
                if ($bool) {
                    $res = ajaxReturnJsonContent::returnVal(!$bool, '修改成功', '修改失败,品牌已存在');
                    return back()->with($res);
                }
            }
            //有则存储
            $res['name'] = $arr['updatename'];
        }
        //判断是否有新的品牌描述传过来
        if ($arr['content']) {
            //有则存储
            $res['desbrand'] = $arr['content'];
        }
        //判断是否有新的图片传过来，有则上传，并获取上传后的图片名存储
        if ($arr['updateBrandpic']) {

            //查询旧图片名
            $img = DB::table('shop_brand')->select('brandpic')
                                          ->where('id', $id)
                                          ->first()
                                          ->Brandpic;

            //上传文件  
            $file = $request->file('updateBrandpic')->store("public/brandpic");

            //处理好图片路径
            $filepath = 'storage'.ltrim($file, 'public');

            //存储新图片名
            $res['brandpic'] = $filepath;

            //删除旧的图片
            unlink($img);
        }

        //判断是否有数据存储
        if ($res == []) {
            //$res为空数组则说明没有新数据过来，则给个提示并返回上一页
            $returnval = ajaxReturnJsonContent::returnVal(!$res, '修改成功', '修改失败');
            return redirect('admin/Brand')->with($returnval);
        }

        $id = DB::table('shop_brand')->where('id', $id)
                                     ->update($res);
        $returnval = ajaxReturnJsonContent::returnVal($res, '修改成功', '修改失败');
        return redirect('admin/Brand')->with($returnval);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $id = rtrim($id, ',').',';
        $id = explode(',', $id);
        array_pop($id);

        //查询数据的图片

        $respic = DB::table('shop_brand')->select('brandpic')
                                       ->whereIn('id', $id)
                                       ->get();

        //删除数据
        $bool = DB::table('shop_brand')->whereIn('id', $id)
                                       ->delete();
        $res = ajaxReturnJsonContent::returnVal($bool, '删除成功', '删除失败');
        if ($res['code'] == 1) {
            foreach($respic as $v) {
                unlink($v->brandpic);
            }
        }
        return back()->with($res);
    }
}
